<template>
  <div ref="elRef" style="min-height: 500px; position: relative">
    <YuFlowNode v-for="node in props.nodeList" :key="node.id" :node="node" :jsplumb="jsplumb">
      <template #default>
        <slot name="node-content" :node="node" :remove="() => handlers.removeNode(node)"></slot>
      </template>
    </YuFlowNode>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, shallowRef } from 'vue';
import { YuFlowLinkType, YuFlowNodeType } from './utils';
import YuFlowNode from './YuFlowNode.vue';
import { newInstance } from '@jsplumb/browser-ui';

interface IProps {
  nodeList: YuFlowNodeType[];
  linkList: YuFlowLinkType[];
}
interface IEmits {
  (e: 'update:nodeList', nodeList: YuFlowNodeType[]);
  (e: 'update:linkList', nodeList: YuFlowLinkType[]);
}
interface ISlots {
  'node-content'(props: { node: YuFlowNodeType; remove(): void }): any;
}

const jsplumb = newInstance({
  container: document.createElement('div'),
  connector: "Straight",
  paintStyle: { strokeWidth: 2, stroke: "#588EF2" },
  endpoint: { type: "Dot", options: { radius: 4 } },
  endpointStyle: { fill: "#9E9E9E" },
  listStyle: {
    endpoint: { type: "Rectangle", options: { width: 30, height: 30 } }
  },
});
const props = defineProps<IProps>();
const emit = defineEmits<IEmits>();
const elRef = shallowRef<HTMLDivElement>();
defineSlots<ISlots>();

onMounted(() => {
  jsplumb.setContainer(elRef.value);
  jsplumb.bind("connection", (conn) => {
    console.log(conn);
  });
  console.log(21312)
  jsplumb.bind("click", function(connection, event) {
    console.log(connection, event,'click');
    // jsPlumb.deleteConnection(connection);
  });
  jsplumb.bind("connectionDetached", (conn) => {
    console.log(conn,'connectionDetached');
  });
  jsplumb.bind("connectionMoved", function(info) {
    console.log(info,'connectionMoved');
  });
  /*jsplumb.bind("dragEnd", (conn) => {
    console.log(conn,'connectionDragEnd');
  });*/
});

const handlers = {
  removeNode(node: YuFlowNodeType) {
    const nodeList = props.nodeList.filter(o => o !== node);
    const linkList = props.linkList.filter(o => o.from !== node.id && o.to !== node.id);
    console.log(nodeList, linkList,'nodeList, linkList');
    emit('update:nodeList', nodeList);
    emit('update:linkList', linkList);
  },
};
function getConnections() {
  let connections = jsplumb.getConnections();
  connections = connections.map((cnx) => {
    console.log(cnx)
    if (cnx.source && cnx.target) {
      const source = `${cnx.source.getAttribute(
        "datapath"
      )}.${cnx.source.getAttribute("datakey")}`;
      const target = `${cnx.target.getAttribute(
        "datapath"
      )}.${cnx.target.getAttribute("datakey")}`;
      return { source, target };
    }
    return { source: null, target: null };
  });
  return connections;
}
</script>
